4.6 kotlin.Unit类型
Kotlin也是面向表达式的语言。在Kotlin中所有控制流语句都是表达式(除了变量赋值、异常等)。
Kotlin中的Unit
类型实现了与Java中的void
一样的功能。不同的是,当一个函数没有返回值的时候,我们用Unit
来表示这个特征,而不是null
。
大多数时候,我们并不需要显式地返回Unit
,或者声明一个函数的返回类型为Unit
。编译器会推断出它。
代码示例:
>>> fun unitExample(){println("Hello,Unit")}
>>> val helloUnit = unitExample()
Hello,Unit
>>> helloUnit
kotlin.Unit
>>> println(helloUnit)
kotlin.Unit
下面几种写法是等价的:
@RunWith(JUnit4::class)
class UnitDemoTest {
@Test fun testUnitDemo() {
val ur1 = unitReturn1()
println(ur1) // kotlin.Unit
val ur2 = unitReturn2()
println(ur2) // kotlin.Unit
val ur3 = unitReturn3()
println(ur3) // kotlin.Unit
}
fun unitReturn1() {
}
fun unitReturn2() {
return Unit
}
fun unitReturn3(): Unit {
}
}
总的来说,这个Unit
类型并没有什么特别之处。它的源码是:
package kotlin
/**
* The type with only one value: the Unit object. This type corresponds to the `void` type in Java.
*/
public object Unit {
override fun toString() = "kotlin.Unit"
}
跟任何其他类型一样,它的父类型是Any
。如果是一个可空的Unit?
,它的父类型是Any?
。
当前内容版权归 JackChan1999 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 JackChan1999 .